pub mod base64;
pub mod csv;
pub mod gen_pass;
pub mod http;
pub mod text;

pub use self::{base64::*, csv::*, gen_pass::*, http::*, text::*};
use clap::Parser;
use enum_dispatch::enum_dispatch;
use std::path::Path;

#[derive(Debug, Parser)]
#[command(name = "rcli", version, author, about, long_about = None)]
pub struct Opts {
    #[command(subcommand)]
    pub cmd: SubCommand,
}

#[derive(Debug, Parser)]
#[enum_dispatch(CmdExecutor)]
pub enum SubCommand {
    #[command(name = "csv", about = "Show CSV, or Convert CSV to other formats")]
    Csv(CsvOpts),
    #[command(name = "gen_pass", about = "Generate Password")]
    GenPass(GenPassOpts),
    #[command(subcommand)]
    Base64(Base64SubCommand),
    #[command(subcommand)]
    Text(TextSubCommand),
    #[command(subcommand)]
    Http(HttpSubCommand),
}
fn verify_file(filename: &str) -> Result<String, String> {
    //如果input是-或者文件已经存在，则返回Ok
    if filename == "-" || Path::new(filename).exists() {
        return Ok(filename.to_string());
    }
    //如果input不是-且文件不存在，则返回Err
    Err(format!("{} is not exist", filename))
}

// impl CmdExecutor for SubCommand {
//     async fn execute(self) -> anyhow::Result<()> {
//         match self {
//             SubCommand::Csv(opts) => opts.execute().await,
//             SubCommand::GenPass(opts) => opts.execute().await,
//             SubCommand::Base64(cmd) => cmd.execute().await,
//             SubCommand::Text(cmd) => cmd.execute().await,
//             SubCommand::Http(cmd) => cmd.execute().await,
//         }
//     }
// }
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_verify_input_file() {
        assert_eq!(verify_file("-"), Ok("-".to_string()));
        assert_eq!(verify_file("*"), Err("* is not exist".to_string()));

        assert_eq!(verify_file("Cargo.toml"), Ok("Cargo.toml".to_string()));
        assert_eq!(
            verify_file("not-exist"),
            Err("not-exist is not exist".to_string())
        );
    }
}
